﻿using AutoMapper;
using BW.MesProject.BasicData.Domain.基础;
using BW.MesProject.BasicData.Infrastructure;
using BW.MesProject.Public.ErrorCode;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Yitter.IdGenerator;
using System;
using System.IO;
using OfficeOpenXml;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;

namespace BW.MesProject.BasicData.Host.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class BomController : ControllerBase
    {
        private readonly IBomServices bomService;
        private readonly IHttpClientFactory _httpClientFactory;

        public BomController(IBomServices bomService, IHttpClientFactory httpClientFactory)
        {
            this.bomService = bomService;
            _httpClientFactory = httpClientFactory;
        }

        /// <summary>
        /// 添加BOM
        /// </summary>
        /// <param name="bommodel">BOM实体</param>
        /// <returns>操作结果</returns>
        [HttpPost]
        public ApiResult<bool> AddBom([FromBody] Bommodel bommodel)
        {
            return bomService.AddBom(bommodel);
        }

        /// <summary>
        /// 添加子集BOM
        /// </summary>
        /// <param name="parentId">父级ID</param>
        /// <param name="childBom">子集BOM实体</param>
        /// <returns>操作结果</returns>
        [HttpPost]
        public ApiResult<bool> AddChildBom(float parentId, [FromBody] Bommodel childBom)
        {
            return bomService.AddChildBom(parentId, childBom);
        }

        /// <summary>
        /// 根据BOM编码查询BOM数据
        /// </summary>
        /// <param name="bomCode">BOM编码，可为空，为空时返回所有未删除的BOM</param>
        /// <returns>符合条件的BOM列表</returns>
        [HttpGet]
        public ApiResult<List<Bommodel>> GetBomsByCode(string? bomCode)
        {
            return bomService.GetBomsByCode(bomCode);
        }

        /// <summary>
        /// 获取BOM详情及其子集
        /// </summary>
        /// <param name="id">BOM ID</param>
        /// <returns>BOM详情和子集</returns>
        [HttpGet]
        public ApiResult<List<Bommodel>> GetBomDetailWithChildren(long id)
        {
            return bomService.GetBomDetailWithChildren(id);
        }

        /// <summary>
        /// 软删除BOM
        /// </summary>
        /// <param name="id">BOM ID</param>
        /// <returns>操作结果</returns>
        [HttpPut]
        public ApiResult<bool> SoftDeleteBom(long id)
        {
            return bomService.SoftDeleteBom(id);
        }

        /// <summary>
        /// 更新BOM信息
        /// </summary>
        /// <param name="bommodel">BOM实体</param>
        /// <returns>操作结果</returns>
        [HttpPost]
        public ApiResult<bool> UpdateBom([FromBody] Bommodel bommodel)
        {
            return bomService.UpdateBom(bommodel);
        }
        //导出
        /// <summary>
        /// 导出BOM数据
        /// </summary>
        /// <param name="bomCode">BOM编码，可为空，为空时导出所有未删除的BOM</param>
        /// <returns>Excel文件流</returns>
        [HttpGet]
        public IActionResult ExportBoms(string? bomCode)
        {
            try
            {
                var result = bomService.GetBomsByCode(bomCode);
                if (result.Code != ApiEnums.Success || result.Data == null)
                {
                    return BadRequest(result.Message);
                }

                // 创建内存流保存Excel
                using var stream = new MemoryStream();
                using var package = new OfficeOpenXml.ExcelPackage(stream);
                var worksheet = package.Workbook.Worksheets.Add("BOM数据");

                // 添加表头
                worksheet.Cells[1, 1].Value = "BOM编码";
                worksheet.Cells[1, 2].Value = "BOM名称";
                worksheet.Cells[1, 3].Value = "BOM版本";
                worksheet.Cells[1, 4].Value = "产品物料编号";
                worksheet.Cells[1, 5].Value = "BOM类型";
                worksheet.Cells[1, 6].Value = "阶别";
                worksheet.Cells[1, 7].Value = "工序编码";
                worksheet.Cells[1, 8].Value = "工序名称";
                worksheet.Cells[1, 9].Value = "用量";
                worksheet.Cells[1, 10].Value = "描述";

                // 设置表头样式
                using (var range = worksheet.Cells[1, 1, 1, 10])
                {
                    range.Style.Font.Bold = true;
                    range.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
                    range.Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.LightGray);
                    range.Style.Border.BorderAround(OfficeOpenXml.Style.ExcelBorderStyle.Thin);
                }

                // 填充数据
                for (int i = 0; i < result.Data.Count; i++)
                {
                    var bom = result.Data[i];
                    worksheet.Cells[i + 2, 1].Value = bom.Bomcode;
                    worksheet.Cells[i + 2, 2].Value = bom.Bomname;
                    worksheet.Cells[i + 2, 3].Value = bom.Bomversion;
                    worksheet.Cells[i + 2, 4].Value = bom.Productitemid;
                    worksheet.Cells[i + 2, 5].Value = bom.BomType;
                    worksheet.Cells[i + 2, 6].Value = bom.Bomranks;
                    worksheet.Cells[i + 2, 7].Value = bom.Processmanagementcode;
                    worksheet.Cells[i + 2, 8].Value = bom.Processmanagementname;
                    worksheet.Cells[i + 2, 9].Value = bom.Bomdosage;
                    worksheet.Cells[i + 2, 10].Value = bom.Bomdescription;
                }

                // 自动调整列宽
                worksheet.Cells.AutoFitColumns();
                
                // 保存Excel
                package.Save();
                
                // 重置流位置
                stream.Position = 0;

                // 返回Excel文件
                string fileName = $"BOM数据_{DateTime.Now:yyyyMMddHHmmss}.xlsx";
                return File(stream.ToArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", fileName);
            }
            catch (Exception ex)
            {
                return BadRequest($"导出失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 导出BOM树结构
        /// </summary>
        /// <param name="id">BOM ID</param>
        /// <returns>Excel文件流</returns>
        [HttpGet]
        public IActionResult ExportBomTree(long id)
        {
            try
            {
                var result = bomService.GetBomDetailWithChildren(id);
                if (result.Code != ApiEnums.Success || result.Data == null)
                {
                    return BadRequest(result.Message);
                }

                // 创建内存流保存Excel
                using var stream = new MemoryStream();
                using var package = new OfficeOpenXml.ExcelPackage(stream);
                var worksheet = package.Workbook.Worksheets.Add("BOM树结构");

                // 添加表头
                worksheet.Cells[1, 1].Value = "层级";
                worksheet.Cells[1, 2].Value = "BOM编码";
                worksheet.Cells[1, 3].Value = "BOM名称";
                worksheet.Cells[1, 4].Value = "BOM版本";
                worksheet.Cells[1, 5].Value = "产品物料编号";
                worksheet.Cells[1, 6].Value = "BOM类型";
                worksheet.Cells[1, 7].Value = "阶别";
                worksheet.Cells[1, 8].Value = "工序编码";
                worksheet.Cells[1, 9].Value = "工序名称";
                worksheet.Cells[1, 10].Value = "用量";
                worksheet.Cells[1, 11].Value = "描述";

                // 设置表头样式
                using (var range = worksheet.Cells[1, 1, 1, 11])
                {
                    range.Style.Font.Bold = true;
                    range.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
                    range.Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.LightGray);
                    range.Style.Border.BorderAround(OfficeOpenXml.Style.ExcelBorderStyle.Thin);
                }

                // 获取父级BOM
                var parentBom = result.Data.FirstOrDefault();
                if (parentBom != null)
                {
                    int rowIndex = 2;
                    
                    // 添加父级BOM
                    worksheet.Cells[rowIndex, 1].Value = "0";
                    worksheet.Cells[rowIndex, 2].Value = parentBom.Bomcode;
                    worksheet.Cells[rowIndex, 3].Value = parentBom.Bomname;
                    worksheet.Cells[rowIndex, 4].Value = parentBom.Bomversion;
                    worksheet.Cells[rowIndex, 5].Value = parentBom.Productitemid;
                    worksheet.Cells[rowIndex, 6].Value = parentBom.BomType;
                    worksheet.Cells[rowIndex, 7].Value = parentBom.Bomranks;
                    worksheet.Cells[rowIndex, 8].Value = parentBom.Processmanagementcode;
                    worksheet.Cells[rowIndex, 9].Value = parentBom.Processmanagementname;
                    worksheet.Cells[rowIndex, 10].Value = parentBom.Bomdosage;
                    worksheet.Cells[rowIndex, 11].Value = parentBom.Bomdescription;
                    
                    rowIndex++;
                    
                    // 添加子级BOM
                    foreach (var childBom in result.Data.Skip(1))
                    {
                        worksheet.Cells[rowIndex, 1].Value = "1";
                        worksheet.Cells[rowIndex, 2].Value = childBom.Bomcode;
                        worksheet.Cells[rowIndex, 3].Value = childBom.Bomname;
                        worksheet.Cells[rowIndex, 4].Value = childBom.Bomversion;
                        worksheet.Cells[rowIndex, 5].Value = childBom.Productitemid;
                        worksheet.Cells[rowIndex, 6].Value = childBom.BomType;
                        worksheet.Cells[rowIndex, 7].Value = childBom.Bomranks;
                        worksheet.Cells[rowIndex, 8].Value = childBom.Processmanagementcode;
                        worksheet.Cells[rowIndex, 9].Value = childBom.Processmanagementname;
                        worksheet.Cells[rowIndex, 10].Value = childBom.Bomdosage;
                        worksheet.Cells[rowIndex, 11].Value = childBom.Bomdescription;
                        
                        rowIndex++;
                    }
                }

                // 自动调整列宽
                worksheet.Cells.AutoFitColumns();
                
                // 保存Excel
                package.Save();
                
                // 重置流位置
                stream.Position = 0;

                // 返回Excel文件
                string fileName = $"BOM树结构_{DateTime.Now:yyyyMMddHHmmss}.xlsx";
                return File(stream.ToArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", fileName);
            }
            catch (Exception ex)
            {
                return BadRequest($"导出失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 同步BOM数据
        /// </summary>
        /// <returns>同步结果</returns>
        [HttpGet]
        public async Task<ApiResult<string>> SyncBomData()
        {
            int addedCount = 0;
            int updatedCount = 0;
            int deletedCount = 0;
            int errorCount = 0;
            List<string> errorMessages = new List<string>();

            try
            {
                // 创建HTTP客户端
                var client = _httpClientFactory.CreateClient();
                client.Timeout = TimeSpan.FromMinutes(5); // 设置较长的超时时间
                
                // 从外部接口获取BOM数据
                var response = await client.GetAsync("http://localhost:5110/api/Bom/GetBom");
                
                if (!response.IsSuccessStatusCode)
                {
                    return new ApiResult<string>
                    {
                        Code = ApiEnums.Fail,
                        Message = $"获取外部BOM数据失败: {response.StatusCode}",
                        Data = null
                    };
                }

                // 读取响应内容
                var content = await response.Content.ReadAsStringAsync();
                
                // 尝试解析不同的响应格式
                List<Bommodel> externalBomData;
                try
                {
                    // 尝试直接解析为BOM列表
                    externalBomData = JsonSerializer.Deserialize<List<Bommodel>>(content, new JsonSerializerOptions
                    {
                        PropertyNameCaseInsensitive = true
                    });
                }
                catch
                {
                    // 尝试解析为ApiResult<List<Bommodel>>格式
                    try
                    {
                        var apiResult = JsonSerializer.Deserialize<ApiResult<List<Bommodel>>>(content, new JsonSerializerOptions
                        {
                            PropertyNameCaseInsensitive = true
                        });
                        
                        externalBomData = apiResult?.Data ?? new List<Bommodel>();
                        
                        if (apiResult?.Code != ApiEnums.Success)
                        {
                            return new ApiResult<string>
                            {
                                Code = ApiEnums.Fail,
                                Message = $"外部API返回错误: {apiResult?.Message}",
                                Data = null
                            };
                        }
                    }
                    catch (Exception ex)
                    {
                        return new ApiResult<string>
                        {
                            Code = ApiEnums.Error,
                            Message = $"解析外部BOM数据失败: {ex.Message}",
                            Data = content.Length > 100 ? content.Substring(0, 100) + "..." : content
                        };
                    }
                }

                if (externalBomData == null || !externalBomData.Any())
                {
                    return new ApiResult<string>
                    {
                        Code = ApiEnums.Fail,
                        Message = "外部BOM数据为空",
                        Data = null
                    };
                }

                Console.WriteLine($"从外部API获取到 {externalBomData.Count} 条BOM数据");

                // 获取本地所有BOM数据
                var localBomResult = bomService.GetBomsByCode(null);
                var localBoms = localBomResult.Data ?? new List<Bommodel>();
                
                Console.WriteLine($"本地数据库中有 {localBoms.Count} 条BOM数据");
                
                // 获取外部BOM的ID列表
                var externalBomIds = externalBomData.Select(b => b.Id).ToList();
                
                // 获取本地BOM的ID列表
                var localBomIds = localBoms.Select(b => b.Id).ToList();

                // 1. 添加或更新BOM
                foreach (var externalBom in externalBomData)
                {
                    try
                    {
                        // 检查本地是否存在该BOM
                        if (localBomIds.Contains(externalBom.Id))
                        {
                            // 更新已存在的BOM
                            var result = bomService.UpdateBom(externalBom);
                            if (result.Code == ApiEnums.Success)
                            {
                                updatedCount++;
                            }
                            else
                            {
                                errorCount++;
                                errorMessages.Add($"更新BOM ID {externalBom.Id} 失败: {result.Message}");
                            }
                        }
                        else
                        {
                            // 再次检查ID是否存在（防止违反唯一约束）
                            var existingBom = bomService.GetBomDetailWithChildren(externalBom.Id);
                            if (existingBom.Data != null && existingBom.Data.Any())
                            {
                                // 如果ID已存在，执行更新而不是添加
                                var result = bomService.UpdateBom(externalBom);
                                if (result.Code == ApiEnums.Success)
                                {
                                    updatedCount++;
                                }
                                else
                                {
                                    errorCount++;
                                    errorMessages.Add($"更新BOM ID {externalBom.Id} 失败: {result.Message}");
                                }
                            }
                            else
                            {
                                // 添加新BOM，保持ID不变
                                var result = bomService.AddBom(externalBom);
                                if (result.Code == ApiEnums.Success)
                                {
                                    addedCount++;
                                }
                                else
                                {
                                    errorCount++;
                                    errorMessages.Add($"添加BOM ID {externalBom.Id} 失败: {result.Message}");
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        // 记录错误但继续处理其他BOM
                        errorCount++;
                        errorMessages.Add($"处理BOM ID {externalBom.Id} 时出错: {ex.Message}");
                        Console.WriteLine($"处理BOM ID {externalBom.Id} 时出错: {ex.Message}");
                    }
                }

                // 2. 删除本地有但外部没有的BOM
                var bomsToDelete = localBomIds.Except(externalBomIds).ToList();
                foreach (var bomId in bomsToDelete)
                {
                    try
                    {
                        var result = bomService.SoftDeleteBom(bomId);
                        if (result.Code == ApiEnums.Success)
                        {
                            deletedCount++;
                        }
                        else
                        {
                            errorCount++;
                            errorMessages.Add($"删除BOM ID {bomId} 失败: {result.Message}");
                        }
                    }
                    catch (Exception ex)
                    {
                        errorCount++;
                        errorMessages.Add($"删除BOM ID {bomId} 时出错: {ex.Message}");
                    }
                }

                string resultMessage = $"BOM数据同步完成，添加: {addedCount}条, 更新: {updatedCount}条, 删除: {deletedCount}条";
                if (errorCount > 0)
                {
                    resultMessage += $", 错误: {errorCount}条";
                }

                return new ApiResult<string>
                {
                    Code = errorCount > 0 ? ApiEnums.PartialSuccess : ApiEnums.Success,
                    Message = resultMessage,
                    Data = errorMessages.Count > 0 ? string.Join("\n", errorMessages.Take(10)) : null
                };
            }
            catch (Exception ex)
            {
                return new ApiResult<string>
                {
                    Code = ApiEnums.Error,
                    Message = $"BOM数据同步失败: {ex.Message}",
                    Data = ex.StackTrace
                };
            }
        }
    }
}
